<!-- 结算单 -->
<template>
    <div class="container">
        <div class="search_form">
            <div>
                <!-- 头部搜索模块 -->
                <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick"
                    :buttonList="buttonList" />
            </div>
        </div>
        <div class="workLineInfo_Plan" style="margin-bottom: 10px">
            <!-- 中间表格模块 -->
            <BaseTable ref="baseTableCheckRef" :data="settlementtableData" :columns="settlementtableDataColumns"
                :tableHeight="0.6*tableHeight" :Propsref="'ticketTable'" :onSelectChange="()=>{}" :loading="loading" @checkId="workTaskSelChange" @details="handlerClick"
                :pagination="queryAll" @size-change="sizeChange" @current-change="pageChange"></BaseTable>
        </div>
        <div class="search_form" style="height: 30px;">
            <div style="margin-left: 16px; float: left">
                <label style="">明细：</label>
            </div>
        </div>
        <div style="border: 1px solid rgba(225, 228, 235, 1)">
            <BaseTable :data="writeOffTableData" :columns="writeOffColumns" :tableHeight="0.4*tableHeight" :pagination="false">
            </BaseTable>
        </div>
        <!-- 销账弹窗 -->
        <el-drawer :before-close="handleClose" title="销账" :visible.sync="drawerInner" direction="rtl" size="52%">
            <detail ref="detailRef" @drawerInner="drawerInnerFun" />
        </el-drawer>
        <!-- 发票登记 -->
        <el-drawer :before-close="handleClose" title="发票登记" :visible.sync="drawerInvoice" direction="rtl" size="52%">
            <div slot="title" class="dialog-title">
                <el-row>
                    <span class="dialog-title-text">发票登记</span>
                    <el-button style="float:right" icon="el-icon-plus" size="mini"
                        v-hasPermi="['businessDataSubsystem:statement:insertkp']" @click="locationAddInvoice"></el-button>
                </el-row>
            </div>
            <BaseTable :data="invoiceData" :columns="invoiceColumns" :tableHeight="tableHeight + 50" :pagination="false">
            </BaseTable>
        </el-drawer>
        <!-- 新增/修改发票 -->
        <el-drawer :before-close="handleClose" :title="title" :visible.sync="addShow" direction="rtl" size="28%">
            <el-form ref="formDataRef" :rules="locationRules" status-icon size="small" :model="formData"
                style="padding:20px">
                <el-form-item label="发票编号" prop="invoiceNo" :label-width="formLabelWidth">
                    <el-input v-model="formData.invoiceNo" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="金额" prop="amount" :label-width="formLabelWidth">
                    <el-input v-model="formData.amount" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="开票日期" prop="invoiceDate" :label-width="formLabelWidth">
                    <el-date-picker style="width: 100%;" v-model="formData.invoiceDate" type="date"
                        value-format="yyyy-MM-dd" placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
                <el-button size="small" type="primary" @click="postList" :loading="loading">{{
                    loading ?
                    '提交中 ...' : '保 存'
                }}</el-button>
            </div>
        </el-drawer>
        <!-- 设置统计月份 -->
        <el-dialog title="设置统计月份" :visible.sync="showDialog" width="30%" :before-close="handleClose">
            月份：
            <el-date-picker style="margin-left: 20px;" value-format="yyyy-MM" v-model="month" type="month"
                placeholder="选择月">
            </el-date-picker>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelClick">取 消</el-button>
                <el-button type="primary" @click="defineClick">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 账期延期 -->
        <el-drawer :before-close="handleClose" :visible.sync="drawerDefer" direction="rtl" size="40%">
            <div slot="title" class="dialog-title">
                <el-row>
                    <span class="dialog-title-text">账期延期</span>
                    <el-button style="float:right" icon="el-icon-plus" size="mini"
                        v-hasPermi="['businessDataSubsystem:statement:insertkp']" @click="deferAdd"></el-button>
                </el-row>
            </div>
            <BaseTable :data="deferData" :columns="deferColumns" :tableHeight="tableHeight + 50" :pagination="false">
            </BaseTable>
        </el-drawer>
        <!-- 添加账期延期 -->
        <el-dialog title="添加账期延期" :visible.sync="dialogAddDefer" width="40%" :before-close="handleClose">
            <el-form label-width="100px" :model="deferForm">
                <el-form-item label="延期前日期">
                    <el-input v-model="deferForm.preDate" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="延期截止日期">
                    <el-date-picker @change="timeChange" style="width: 100%;" value-format="yyyy-MM-dd"
                        v-model="deferForm.postponeDate" type="date" placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="延期天数">
                    <el-input-number v-model="deferForm.postponeDays" @change="changeDays" :min="0" :max="99999"
                        label="描述文字"></el-input-number>
                </el-form-item>
                <el-form-item label="附件">
                    <Upload @changeFile="changeFile" :fileListEdit="deferForm.mattachmentInfoList" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelAddDefer">取 消</el-button>
                <el-button type="primary" @click="defineAddDefer">添 加</el-button>
            </span>
        </el-dialog>
        <!-- 附件查询 -->
        <el-dialog title="账期延期附件" :visible.sync="openFile" width="30%" :before-close="handleClose" append-to-body>
            <div v-for="(item, index) in fileList" :key="item.fileId" @click="handlePreview(item)"
                style="cursor:pointer;margin: 5px 0;">{{ index + 1 }}、{{ item.fileName }}
            </div>
            <el-empty description="未上传附件" v-if="fileList.length === 0"></el-empty>
        </el-dialog>
        <!-- 图片查看 -->
        <el-dialog :visible.sync="dialogVisible" width="50%" :before-close="handleClose" append-to-body>
            <img style="width: 100%; height: 100%;" :src="imgurl" alt="">
        </el-dialog>
        <!-- 打印 -->
        <print-preview ref="printPreview" :printData="printData"  :rateTypeCode="rateTypeCode"/>
    </div>
</template>

<script>
import BaseTableCheck from '@/components/BaseTable/baseTablecheck'
import headerSearch from '@/components/headerSearch'
import BaseTable from '@/components/BaseTable'
import publicapi from '@/api/public'
import detail from './detail.vue'
import api from '@/api/Business/statement'
import dfilters from '@/libs/Utils.js'
import Upload from '@/components/upload'
import axios from 'axios'
import config from '@/network/config.js'
// 打印
import printPreview from '@/components/print/printPreview.vue'
export default {
  components: {
    BaseTable,
    headerSearch,
    detail,
    BaseTableCheck,
    Upload,
    printPreview
  },
  data() {
    var that = this
    return {
      loading: false,
      menuFlag: false,
      menuArr: [],
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipName',
          selectData: [],
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageName'
        },
        {
          name: '付费方',
          type: 'select',
          modelName: 'payCompanyName',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '选择状态',
          type: 'select',
          modelName: 'status',
          selectData: [
            {
              dictValue: '1',
              dictLabel: '未审核'
            }, {
              dictValue: '2',
              dictLabel: '已审核'
            }
          ],
          selectLabel: 'dictLabel',
          selectValue: 'dictValue'
        },
        {
          name: '收费方',
          type: 'select',
          modelName: 'chargeCompanyCode',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '费用分类',
          type: 'select',
          modelName: 'rateTypeCode',
          selectData: [],
          selectLabel: 'dictLabel',
          selectValue: 'dictValue'
        },
        {
          name: '账单日期',
          type: 'date',
          modelName: 'data'
        }

      ],
      // header的按钮list
      buttonList: [
        { label: '批量销账', disabled: false, type: 'primary', icon: 'el-icon-document-checked', click: () => this.writeOffInfomation, permission: 'businessDataSubsystem:statement:writeOff' },
        { label: '发票登记', disabled: false, type: 'primary', icon: 'el-icon-edit-outline', click: () => this.invoiceRegister, permission: 'businessDataSubsystem:statement:register' },
        { label: '统计月份', type: 'primary', icon: 'el-icon-pie-chart', click: () => this.setupMonth, permission: 'businessDataSubsystem:statement:insertMonth' },
        { label: '账期延期', disabled: false, type: 'primary', icon: 'el-icon-timer', click: () => this.deferClick, permission: 'businessDataSubsystem:statement:insertPostpone' }
      ],
      settlementtableData: [],
      settlementtableDataColumns: [ // table表头
      { type: 'selection', width: 50 },
        {
          width: 150,
          prop: 'statementNo',
          label: '结算单号'
        },
        {
          width: 100,
          prop: 'rateTypeName',
          label: '费用分类'
        },
        {
          width: 100,
          prop: 'chargeCompanyName',
          isShort: true,
          label: '收费方'
        },
        {
          width: 100,
          prop: 'payCompanyName',
          isShort: true,
          label: '付费方'
        },
        {
          width: 100,
          prop: 'shipName',
          label: '船名航次'
        },
        {
          width: 100,
          prop: 'cargoName',
          label: '货名'
        },
        {
          width: 170,
          prop: 'berthTime',
          label: '靠泊时间'
        },
        {
          width: 100,
          prop: 'totalAmount',
          label: '账单金额',
          isMoney: true
        },
        {
          width: 120,
          prop: 'settlementDate',
          label: '账单日期'
        },
        {
          width: 120,
          prop: 'month',
          label: '统计月份'
        },
        {
          width: 100,
          prop: 'zqn',
          label: '账期内回款',
          isMoney: true
        },
        {
          width: 100,
          prop: 'zqw',
          label: '账期外回款',
          isMoney: false
        },
        {
          width: 100,
          prop: 'yj',
          label: '预缴回款',
          isMoney: true
        },
        {
          width: 120,
          prop: 'paymentDate',
          label: '账期'
        },
        {
          width: 100,
          prop: 'qk',
          label: '欠款金额',
          isMoney: true
        },
        {
          width: 100,
          prop: 'invoiceAmount',
          label: '开票金额',
          isMoney: true
        },
        {
          prop: 'status',
          label: '账单状态',
          fixed: 'right',
          width: 80,
          render(h, params) {
            if (params.row.status == '2') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'success'
                },
                domProps: {
                  innerHTML: '已审核'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'danger'
              },
              domProps: {
                innerHTML: '未审核'
              }
            })
          }
        },
        {
          label: '操作',
          width: 80,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              {
                calss: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;'><i class='el-icon-receiving'></i><span  style='padding-left:5px;'>打印</span></span>`
                  },
                  on: {
                    click: () => {
                      this.printClick(params.$index, params.row)
                    }
                  }
                })
              ]
            )
          }
        }],
      queryAll: {
        totalNum: 0,
        startpage: 1,
        pagesize: 10
      },
      writeOffTableData: [],
      writeOffColumns: [
        {
          prop: 'rateItemName',
          label: '费目'
        },
        {
          prop: 'dictLabel',
          label: '计量单位'
        },
        {
          prop: 'rate',
          label: '单价',
          isMoney: true
        },
        {
          prop: 'quantity',
          label: '数量'
        },
        {
          prop: 'amount',
          label: '金额',
          isMoney: true
        }
      ],
      drawerInner: false,
      batchData: {
        payCompanyName: '',
        chargeCompanyName: ''
      },
      batchList: [],
      rateTypeList: [],
      // 发票登记
      drawerInvoice: false,
      invoiceData: [],
      invoiceColumns: [
        {
          prop: 'invoiceNo',
          label: '发票编号'
        },
        {
          prop: 'amount',
          label: '金额'
        },
        {
          prop: 'invoiceDate',
          label: '开票日期'
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 300,
          render: (h, params) => {
            return h(
              'div',
              {
                calss: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.delFlag == '1'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('修改开票') ? 'block' : 'none'}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.locationUpdateModel(params.$index, params.row)
                    }
                  }
                }),

                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  domProps: {
                    innerHTML: `<span style='color:#F75E5E;display: ${this.menuArr.includes('删除开票') ? 'block' : 'none'}'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleDelete('2', params.row.id)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      invoiceMsg: '',
      // 发票新增修改
      addShow: false,
      title: '',
      formData: {
        statementId: '',
        invoiceNo: '',
        amount: '',
        invoiceDate: ''
      },
      locationRules: {
        invoiceNo: [
          {
            required: true,
            message: '请输入发票编号',
            trigger: 'blur'
          }
        ],
        amount: [
          {
            required: true,
            message: '请输入金额',
            trigger: 'blur'
          }
        ],
        invoiceDate: [
          {
            required: true,
            message: '请选择时间',
            trigger: 'blur'
          }
        ]
      },
      formLabelWidth: '100px', // form的item宽度
      showDialog: false,
      month: '',
      drawerDefer: false,
      deferData: [],
      deferColumns: [
        {
          prop: 'preDate',
          label: '延期前日期'
        },
        {
          prop: 'postponeDate',
          label: '延期截止日期'
        },
        {
          prop: 'postponeDays',
          label: '延期天数'
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 200,
          render: (h, params) => {
            return h(
              'div',
              {
                calss: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('修改开票') ? 'block' : 'none'}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>查看附件</span></span>`
                  },
                  on: {
                    click: () => {
                      this.lookAnnex(params.row)
                    }
                  }
                }),
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.index != 0
                  },
                  domProps: {
                    innerHTML: `<span style='color:#F75E5E;display: ${this.menuArr.includes('删除开票') ? 'block' : 'none'}'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.deleteDefer(params.$index, params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      dialogAddDefer: false,
      deferForm: {
        preDate: '',
        postponeDate: '',
        postponeDays: '',
        mattachmentInfoList: []
      },
      openFile: false,
      fileList: [], // 预览附件
      dialogVisible: false,
      imgurl: '',
      rateTypeCode: '',
      printData: {
        name: '', // 没用
        logoTest: 'https://portrait.gitee.com/uploads/avatars/user/1800/5400665_CcSimple_1591166830.png!avatar60', // 还用这个就行
        statementNo: '', // NO
        shipName: '', // 船名
        tradeType: '', // 类型
        leaveBerthTime: '', // 离港日期
        payCompanyName: '', // 结算单位
        invoiceDate: '', // 计费
        userName: '', // 制表人
        totalAmount: '', // 合计金额
        totalAmountBig: '', // 合计金额大写
        table: []
      }
    }
  },
  async activated() {
    var menuArr = []
    var menuId = ''
    if (localStorage.getItem('menuArr')) {
      menuArr = JSON.parse(localStorage.getItem('menuArr'))
    }
    menuArr.map(item => {
      item.children.map(v => {
        if (window.location.href.includes(v.url)) {
          menuId = v.id
        }
      })
    })
    if (menuId) {
      this.menuArr = []
      await this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`, { timeout: 30000 })
        .then(res => {
          res.data.data.map(item => {
            this.menuArr.push(item.RESOURCENAME)
          })
        }).catch((error) => { })
    }
    if (this.$store.state.app.searchResouce === 'menu') {
      // this.queryAll = {
      //     startpage: 1,
      //     pagesize: 10,
      //     totalNum: 0,
      // }
    }
    this.getShipvoyage()
    this.getCustomer()
    this.getRateTypeData()
  },
  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight - 60
    }
  },
  methods: {
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
      this.selectObject[0].selectData = this.shipVoyageData
    },
    /**
     * 获取客户信息
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.customerData = res.data.data
      console.log(this.customerData);
      this.selectObject[1].selectData = this.customerData
      this.selectObject[3].selectData = this.customerData
    },
    // 字典查询费用类型
    async getRateTypeData() {
      const res = await publicapi.getDictData('RATE_TYPE')
      this.rateTypeList = res.data.data.RATE_TYPE
      this.selectObject[4].selectData = this.rateTypeList
    },
    // 获取数据
    async getDataList() {
      this.loading = true
      this.$refs.baseTableCheckRef.clearSelection()
      await api.getCostStatementController(this.queryAll).then(res => {
        if (res.status == '200') {
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.settlementtableData = res.data.data.pages
          this.settlementtableData.forEach(item => {
            item.amount ? item.amount : 0
            item.settlementDate = dfilters.getProcessingDate(item.settlementDate, '3')
            item.berthTime = dfilters.getProcessingDate(item.berthTime, '0')
            item.paymentDate = dfilters.getProcessingDate(item.paymentDate, '3')
          })
          this.loading = false
        }
      })
    },
    // 点击批量销账
    writeOffInfomation() {
      this.batchData.payCompanyName = ''
      this.batchData.chargeCompanyName = ''
      if (this.batchList.length > '1') {
        var m = this.batchList[0].payCompanyName
        var d = this.batchList[0].chargeCompanyName
        if (this.batchList.every(item => item.payCompanyName === m) || this.batchList.every(item => item.chargeCompanyName === d)) {
          if (!this.drawerInner) {
            this.drawerInner = true
          }
          this.batchData.payCompanyName = m
          this.batchData.chargeCompanyName = d
          this.getBatchList()
        } else {
          return this.$message.warning('请选择收费方和付费方相同的数据')
        }
      } else if (this.batchList.length == '1') {
        if (!this.drawerInner) {
          this.drawerInner = true
        }
        this.batchData.payCompanyName = this.batchList[0].payCompanyName
        this.batchData.chargeCompanyName = this.batchList[0].chargeCompanyName
        this.getBatchList()
      } else {
        return this.$message.warning('请先勾选数据')
      }
    },
    // 获取数据
    async getBatchList() {
      await api.getDataListQueryBy(this.batchData).then(res => {
        if (res.status == '200') {
          const msg = res.data.data
          this.$refs.detailRef.updateData(msg, this.batchList)
        }
      })
    },
    workTaskSelChange(val) {
      this.batchList = val
      this.buttonList.forEach(msg => {
        if (this.batchList.filter(item => item.status == 1).length > 0) {
          msg.disabled = true
        } else {
          if (this.batchList.length > 1) {
            for (let i = 0; i < this.batchList.length; i++) {
              if (this.batchList[i].chargeCompanyId == this.batchList[i + 1].chargeCompanyId && this.batchList[i].payCompanyId == this.batchList[i + 1].payCompanyId && this.batchList[i].status == '1') {
                msg.disabled = false
              } else {
                msg.disabled = true
              }
            }
          } else if (this.batchList.length == 1) {
            msg.disabled = true
          } else {
            msg.disabled = false
          }
          msg.disabled = false
        }
      })
    },
    // 单击主列表
    async handlerClick(row) {
      this.invoiceMsg = ''
      this.invoiceMsg = row
      if (!this.invoiceMsg.paymentDate) {
        this.buttonList.filter(item => item.label == '账期延期')[0].disabled = true
      } else {
        this.buttonList.filter(item => item.label == '账期延期')[0].disabled = false
      }
      this.writeOffTableData = []
      await api.getDataListById(row.id).then(res => {
        if (res.data.code == '0000') {
          this.writeOffTableData = res.data.data
        }
      })
    },
    // 查询
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.invoiceMsg = ''
      this.getDataList()
    },
    // 子页面取消按钮
    drawerInnerFun() {
      this.drawerInner = false
      this.getDataList()
    },
    // 发票登记
    async invoiceRegister() {
      if (this.invoiceMsg) {
        if (!this.drawerInvoice) {
          this.drawerInvoice = true
        }
        await api.getInvoiceData(this.invoiceMsg.id).then(res => {
          if (res.status == '200') {
            this.invoiceData = res.data.data
            this.invoiceData.map(item => {
              item.invoiceDate = dfilters.getProcessingDate(item.invoiceDate, '3')
            })
          }
        })
      } else {
        return this.$message.warning('请选择一条结算单')
      }
    },
    // 新增发票
    locationAddInvoice() {
      if (!this.addShow) {
        this.addShow = true
      }
      this.title = '新增发票'
      this.formData = this.$options.data().formData
    },
    // 保存发票
    async postList() {
      if (this.invoiceMsg) {
        this.formData.statementId = this.invoiceMsg.id
      }
      if (this.title == '新增发票') {
        await api.addInvoiceData(this.formData).then(res => {
          if (res.status == '200') {
            this.addShow = false
            this.invoiceRegister()
            this.getDataList()
            return this.$message.success(res.data.msg)
          }
        })
      } else {
        const form = {
          id: this.formData.id,
          statementId: this.invoiceMsg.id,
          invoiceNo: this.formData.invoiceNo,
          amount: this.formData.amount,
          invoiceDate: this.formData.invoiceDate
        }
        await api.changeInvoiceData(form).then(res => {
          if (res.status == '200') {
            this.addShow = false
            this.invoiceRegister()
            this.getDataList()
            return this.$message.success(res.data.msg)
          }
        })
      }
    },
    // 编辑按钮
    async locationUpdateModel(val, row) {
      this.title = '修改发票'
      await api.getInvoiceById(row.id).then(res => {
        if (res.status == '200') {
          this.addShow = true
          this.formData = res.data.data
        }
      })
    },
    // 删除按钮
    async handleDelete(val, id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => { })
      if (confirmRes !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      this.subDelete(id)
    },
    async subDelete(id) {
      const params = {
        id: id,
        statementId: this.invoiceMsg.id
      }
      await api.deleteInvoiceData(params).then(res => {
        if (res.status == '200') {
          this.invoiceRegister()
          this.getDataList()
          return this.$message.success(res.data.msg)
        }
      })
    },
    // 统计月份按钮
    setupMonth() {
      if (!this.invoiceMsg.id) {
        return this.$message.warning('请选择一条结算单')
      }
      if (!this.showDialog) {
        this.month = ''
        this.showDialog = true
      }
    },
    // 确定统计月份
    async defineClick() {
      const data = {
        id: this.invoiceMsg.id,
        month: this.month
      }
      await api.changeMonth(data).then(res => {
        if (res.data.code == '0000') {
          this.$message.success(res.data.msg)
          this.getBatchList()
          this.showDialog = false
        }
      })
    },
    // 取消统计月份
    cancelClick() {
      if (this.showDialog) {
        this.showDialog = false
      }
      this.month = 1
    },
    // 账期延期按钮
    deferClick() {
      if (!this.invoiceMsg.id) {
        return this.$message.warning('请选择一条结算单')
      }
      if (!this.drawerDefer) {
        this.drawerDefer = true
        this.getData()
      }
    },
    // 请求延期信息接口
    async getData() {
      await api.getPostpone(this.invoiceMsg.id).then(res => {
        if (res.data.code == '0000') {
          this.deferData = res.data.data
        }
      })
    },
    // 账期延期添加按钮
    deferAdd() {
      if (!this.dialogAddDefer) {
        this.dialogAddDefer = true
        this.deferForm = this.$options.data().deferForm
      }
      if (this.invoiceMsg.paymentDate) {
        this.deferForm.preDate = dfilters.getProcessingDate(this.invoiceMsg.paymentDate, '3')
      } else {
        this.deferForm.preDate = ''
      }
    },
    // 账期延期添加确定
    async defineAddDefer() {
      if (this.deferForm.postponeDays < 0) {
        return this.$message.warning('延期天数必须大于等于0')
      }
      if (!this.deferForm.postponeDate) {
        return this.$message.warning('请输入截止日期')
      }
      if (this.deferForm.mattachmentInfoList.length == 0) {
        return this.$message.warning('请上传附件')
      }
      if (!this.deferForm.preDate) {
        return this.$message.warning('该数据没有延期日期')
      }
      const data = {
        statementId: this.invoiceMsg.id,
        postponeDate: this.deferForm.postponeDate,
        mattachmentInfoList: this.deferForm.mattachmentInfoList,
        postponeDays: this.deferForm.postponeDays,
        preDate: this.deferForm.preDate
      }
      await api.addPostpone(data).then(res => {
        if (res.data.code == '0000') {
          this.$message.success(res.data.msg)
          this.getData()
          if (this.dialogAddDefer) {
            this.dialogAddDefer = false
          }
        }
      })
    },
    // 账期延期添加取消
    cancelAddDefer() {
      if (this.dialogAddDefer) {
        this.dialogAddDefer = false
      }
    },
    // 获取两时间之间的天数
    getDays(time1, time2) {
      const startDate = Date.parse(time1)
      const endDate = Date.parse(time2)
      return (startDate - endDate) / (1 * 24 * 60 * 60 * 1000)
    },
    // 时间修改
    timeChange() {
      if (!this.invoiceMsg.paymentDate) {
        this.$message.warning('账期不存在')
      }
      if (this.deferForm.preDate && this.deferForm.postponeDate) {
        this.deferForm.postponeDays = this.getDays(this.deferForm.postponeDate, this.deferForm.preDate)
      } else {
        this.deferForm.postponeDays = ''
      }
    },
    // 修改天数
    changeDays(val) {
      const time = new Date(this.deferForm.preDate).getTime() + val * 24 * 60 * 60 * 1000
      this.deferForm.postponeDate = new Date(time)
    },
    /**
     * 修改文件
     */
    changeFile(fileList, val, item) {
      this.deferForm.mattachmentInfoList = []
      this.deferForm.mattachmentInfoList = fileList
      if (this.deferForm.mattachmentInfoList && this.deferForm.mattachmentInfoList.length > 0) {
        this.deferForm.mattachmentInfoList.forEach(v => {
          v.fileType = item
        })
      }
    },
    // 查看附件按钮
    async lookAnnex(row) {
      await api.getPostponeById(row.id).then(res => {
        if (res.data.code == '0000') {
          this.openFile = true
          this.fileList = res.data.data.mattachmentInfoList
        }
      })
    },
    /**
     * 预览附件
     */
    handlePreview(file) {
      if (file.fileName.indexOf('jpg') !== -1 || file.fileName.indexOf('png') !== -1 || file.fileName.indexOf('jpeg') !== -1) {
        axios({
          method: 'get',
          url: `${config.ConfigBaseURL}/wfpms-master-service/api/external/publics/file/down?id=${file.fileId}`,
          responseType: 'arraybuffer',
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }).then(res => {
          const blob = new Blob([res.data], {
            type: 'application/png;charset=utf-8'
          });
          const url = window.URL.createObjectURL(blob);
          this.imgurl = url
          this.dialogVisible = true
        })
      } else {
        this.downLoadFile(file)
      }
    },
    /**
     * 下载附件
     */
    async downLoadFile(file) {
      const res = await publicapi.down(file.fileId)
      const content = res.data
      const blob = new Blob([content]) // 构造一个blob对象来处理数据
      const link = document.createElement('a') // 创建a标签
      link.download = file.fileName // a标签添加属性
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob, {
        type: `application/pdf`
      })
      document.body.appendChild(link)
      link.click() // 执行下载
      URL.revokeObjectURL(link.href) // 释放url
      document.body.removeChild(link) // 释放标签
    },
    // 删除按钮
    deleteDefer(index, row) {
      this.$confirm('确认删除？').then(() => {
        api.deletePostpone(row).then(res => {
          if (res.data.code == '0000') {
            this.$message.success(res.data.msg)
            this.getData()
          }
        })
      }).catch(err => { })
    },
    // 打印
    async printClick(index, row) {
      console.log(row);
      this.rateTypeCode = ''
      this.printData = this.$options.data().printData
      this.rateTypeCode = row.rateTypeCode
      console.log(this.rateTypeCode);
      this.printData.payCompanyName = row.payCompanyName
      this.printData.statementNo = row.statementNo
      this.printData.shipName = row.shipName
      this.printData.leaveBerthTime = row.leaveBerthTime
      this.printData.tradeType = row.tradeType
      this.printData.userName = window.sessionStorage.getItem('userName')
      this.printData.invoiceDate = row.settlementDate
      this.printData.totalAmount = row.qk
      this.printData.totalAmountBig = this.digitUppercase(row.qk)
      await api.getDataListById(row.id).then(res => {
        if (res.data.code == '0000') {
          const data = res.data.data
          data.forEach((item, i) => {
            var msg = {
              index: '',
              rateItemName: '',
              cargoTypeName: '',
              unitName: '',
              rate: '',
              quantity: '',
              quantityPlug: '',
              amount: '',
              totalAmount: '',
              remark: ''
            }
            this.printData.table.push(msg)
            this.printData.table[i].index = i + 1
            this.printData.table[i].rateItemName = item.rateItemName
            this.printData.table[i].cargoTypeName = row.cargoName
            this.printData.table[i].unitName = item.dictLabel
            this.printData.table[i].rate = item.rate
            this.printData.table[i].quantity = item.quantity
            this.printData.table[i].amount = item.amount
            this.printData.table[i].totalAmount = item.amount
          })
          this.$refs.printPreview.preView()
        }
      })
    },
    // 金额数字转大写
    digitUppercase(n) {
      var fraction = ['角', '分'];
      var digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
      ];
      var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ];
      n = Math.abs(n);
      var s = '';
      for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
      }
      s = s || '整';
      n = Math.floor(n);
      for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
      }
      return s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
    },
    // 关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
          this.dialogVisible = false
        })
        .catch((_) => { });
    },
    // 每页显示的条数
    sizeChange(val) {
      this.queryAll.pagesize = val
      this.getDataList()
    },
    // 当前页
    pageChange(val) {
      this.queryAll.startpage = val
      this.getDataList()
    }
  }
}
</script>

<style lang="less" scoped>
.container {
	background: #ffffff;
	border: 1px solid #e1e4eb;
	// border-radius: 4px 4px 0 0;
	// border-top: none;
}
.el-dialog-div {
    height: 60vh;
    overflow: auto;
}

// .el-button /deep/ {
//     margin-left: 6px !important;
// }

/deep/ .dialog .el-dialog__body {
    padding-top: 0;
}

/deep/ .dialog .sear .el-form--inline .el-form-item {
    margin-right: 0;
}

/deep/ .commonSearch {
    border-top: none;
    position: absolute;
    z-index: 10;
    width: 100%;
    padding-right: 0;
    box-shadow: 0px 2px 4px 0px #e3e5ee;
    border-bottom: 1px solid #e1e4eb;

    /deep/ .el-input {
        position: relative;
        font-size: 14px;
        display: inline-block;
        width: auto;
    }
}

/deep/ .el-drawer__header {
    margin-bottom: -10px;
    padding: 16px;
    border-bottom: 1px solid gainsboro;
}
</style>
